/****************************************
* James Gomez                           *
* Project 3: Target Practice P3         *
* Comp 465                              *
* Professor Barnes                      *
* 12/7/2012                             *
*****************************************/

#ifndef _SHIP_TORPEDO_
#define _SHIP_TORPEDO_

#include "GomezJamesP3_OpenGL.h"
#include "GomezJamesP3_Torpedo.cpp"

#include "GomezJamesP3_Vector3D.cpp"
#include "GomezJamesP3_MissileBattery.cpp"

#include <vector>

extern ::vector<MissileBattery *> missileSites;

class ShipTorpedo: public Torpedo{

private:
	GLfloat degreeOfRotation;
	MissileBattery * nearest;
	vector<MissileBattery *>::iterator i;
	//int frameCounter;

public:
	ShipTorpedo(const int lifespan, const GLfloat startM[16]);
	~ShipTorpedo(){}

	void seekTarget();
};


ShipTorpedo::ShipTorpedo(const int lifespan, const GLfloat startM[16]): 
	Torpedo(red, 250, startM){
		
	degreeOfRotation = 10.0;
	nearest = NULL;
	//frameCounter = 0;
}

//Override
void ShipTorpedo::seekTarget(){
		
	if (!missileSites.empty()){				

		//find nearest missileSite on the first pass of SeekTarget()
		if (nearest == NULL){
			nearest = missileSites.at(0);
			for(i=missileSites.begin()+1; i<missileSites.end(); i++){		
				if ( (*i)->active() && distance((*i)) < distance(nearest) )
					nearest = (*i);
			}
		}		
		
		//only seek nearest missile site if it's active
		if (nearest->active()){
			Vector3D targetV = nearest->getLocationV();
			targetV.subtract(this->getLocationV());		
		
			Vector3D axis = getAtV().crossProduct(targetV.getNormalizedV());
			axis.normalize();

			Vector3D right = this->getRightV();
			Vector3D left = right.getNegatedV();	
		
			//orient torpedo towards nearest missileSite
			glMatrixMode(GL_MODELVIEW);
			glPushMatrix();
			glLoadMatrixf(OM);
			glRotatef(degreeOfRotation, axis.getX(), axis.getY(), axis.getZ());
			glGetFloatv(GL_MODELVIEW_MATRIX, OM);
			glPopMatrix();
		}
		
		//frameCounter++;
	}
	
}

#endif